# -*- coding：utf-8 -*-
"""
@Time:2024-10-0713:51
@Auth:泛彼泊舟
@File:extract_util.py
@IDE:PyCharm
@模块功能：根据yaml是否提取变量存入到变量中
"""
import copy
import re
from string import Template

import yaml
from jsonpath import jsonpath
from hotload.debug_talk import DebugTalk
from common.yaml.yaml_Util import write_yaml, read_all


class ExtractUtil:
    # 解析提取变量
    def extract(self, res, var_name, attr_name, expr, index):
        """
        :param res: 响应值
        :param var_name: 变量名称
        :param attr_name:
        :param expr: 表达式
        :param index: 索引
        :return:
        """
        # 深拷贝
        new_res = copy.deepcopy(res)
        try:
            new_res.json = new_res.json()
        except Exception:
            new_res.json = {"msg": 'response not json data'}
        # 通过反射获取属性的值
        data = getattr(new_res, attr_name)
        print("data={}".format(data))
        # 判断通过什么提取方式提取数组
        if expr.startswith("$"):
            lis = jsonpath(data, expr)
        else:
            lis = re.findall(expr, data)
        # 通过下标取值
        print("lis={}".format(lis))
        if lis:
            write_yaml({var_name: lis[index]})

    # 解析使用变量,把${token}改成从extarct.yaml里面提取的具体的值
    def change(self, request_data: dict):
        # 1.把字典转成字符串
        data_str = yaml.safe_dump(request_data)
        # 2.字符串替换
        # data_str.replace()
        new_request_data = Template(data_str).safe_substitute(read_all())
        # 3.将字符串还原成字典
        data_dict = yaml.safe_load(new_request_data)
        return data_dict

    # 热加载替换
    def hot_replace(self, data_str: str) -> str:
        # 定义正则匹配这种表达式
        regexp = "\\$\\{(.*?)\\((.*?)\\)\\}"  # ${函数名(参数)}
        # 通过正则表达式在data_str字符串中去匹配，得到所有的表达式list
        fun_list = re.findall(regexp, data_str)
        for f in fun_list:
            if f[1] == "":  # 没有参数
                new_value = getattr(DebugTalk(),f[0])()
            else:       # 有参数，1-N
                new_value = getattr(DebugTalk(),f[0])(*f[1].split(','))
            if isinstance(new_value, str) and new_value.isdigit():
                new_value = "'" + new_value + "'"
            # 拼接旧的值
            old_value = "${"+f[0]+"("+f[1]+")}"
            # print("old_value={}".format(old_value))
            # 把旧的表达式替换成函数返回的新值
            data_str.replace(old_value, str(new_value))

        return data_str
